#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from comm.beans.SysDictObj import SysDictObj
from conn.MyPagerFactory import MyPager


FoodcatAdm = Bottle()



@FoodcatAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@FoodcatAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class FoodCatalogsRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    foodCatalogsServiceImpl = None
    _dict = None

    def __init__(self, pru_tuut_db_conn,foodCatalogsService):
        FoodCatalogsRoute.foodCatalogsServiceImpl = foodCatalogsService
        FoodCatalogsRoute._dict = SysDictObj(pru_tuut_db_conn)
        return

    @staticmethod
    @FoodcatAdm.get('/fetch')
    def fetch():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        res = FoodCatalogsRoute.foodCatalogsServiceImpl.fetch(param=params)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': FoodCatalogsRoute.ERROR_CODE["99"]}
        view_list = res['data']
        _pages = MyPager.make_pager(id="table_subject_msg", res=view_list, page_size=int(params['pageSize']),
                                    data_total=res['total'], single_pager=False)
        return {'code': 200, 'data': _pages, 'message': ""}

    @staticmethod
    @FoodcatAdm.get('/fetchOne')
    def fetch_one():
        id = request.params.id
        res = FoodCatalogsRoute.foodCatalogsServiceImpl.fetch_one(food_id=id)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': FoodCatalogsRoute.ERROR_CODE["99"]}
        view_data = res['data']
        return {'code': 200, 'data': view_data, 'message': ""}

    @staticmethod
    @FoodcatAdm.post('/add')
    def add():
        if request.json is not None:
            data = request.json['data']
            res = FoodCatalogsRoute.foodCatalogsServiceImpl.add_food_catalog(foodCatalog=data)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': res['code'], 'data': res, 'message': FoodCatalogsRoute.ERROR_CODE["100"]}

    @staticmethod
    @FoodcatAdm.post('/update')
    def update():
        if request.json is not None:
            data = request.json['data']
            foodId = request.json['id']
            res = FoodCatalogsRoute.foodCatalogsServiceImpl.update_food_catalog(foodCatalog=data, food_id=foodId)
            if res['code'] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            elif res['code'] == 404:
                return {'code': res['code'], 'data': res, 'message': FoodCatalogsRoute.ERROR_CODE["109"]}
            else:
                return {'code': res['code'], 'data': res, 'message': FoodCatalogsRoute.ERROR_CODE["102"]}

    @staticmethod
    @FoodcatAdm.get('/drop')
    def drop():
        id = request.params.id
        return FoodCatalogsRoute.foodCatalogsServiceImpl.drop_food_catalog(food_id=id)

    @staticmethod
    @FoodcatAdm.get('/loadCustDinner')
    def load_cust_dinner():
        import datetime
        view_list = []
        _choose_cust_dinner = FoodCatalogsRoute._dict.load_dict_val(key_eng="custDinner")["data"]["val"]
        json_data_arry = json.loads(_choose_cust_dinner)
        day_arry = json_data_arry
        for day_idx in range(len(day_arry)):
            day = day_arry[day_idx]
            cal_can_Object = {}
            can_arry = day["can"]
            for can_idx in range(len(can_arry)):
                choosed_dinner_vitamin_array = []
                choosed_dinner_fat_array = []
                choosed_dinner_carbonWater_array = []
                choosed_dinner_protein_array = []
                _can = {}
                food_arry = can_arry[can_idx]["foods"]
                for food_idx in range(len(food_arry)):
                    if food_arry[food_idx]["catalog"] == "碳水化合":
                        choosed_dinner_carbonWater_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "脂肪":
                        choosed_dinner_fat_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "维生素":
                        choosed_dinner_vitamin_array.append(food_arry[food_idx])
                    if food_arry[food_idx]["catalog"] == "蛋白质":
                        choosed_dinner_protein_array.append(food_arry[food_idx])
                cal_can_Object[can_arry[can_idx]["name"]] = {"protein": choosed_dinner_protein_array,
                                                             "vitamin": choosed_dinner_vitamin_array,
                                                             "carbonWater": choosed_dinner_carbonWater_array,
                                                             "fat": choosed_dinner_fat_array}
            str_cal_date = (datetime.datetime.now() + datetime.timedelta(days=day_idx)).strftime(
                "%Y-%m-%d")
            view_list.append({"list": cal_can_Object, "cal_day": str_cal_date})
        return {'code': 200, 'data': view_list, 'message': ""}

    @staticmethod
    @FoodcatAdm.post('/updateCustDinner')
    def update_cust_dinner():
        if request.json is not None:
            param_data = request.json['data']
            _days = []
            for _i in param_data:
                ary_can = []
                _ary_can_list = _i["list"]
                _can = {}
                for key, value in _ary_can_list.items():
                    foods = []
                    [foods.append(_z) for _z in value["protein"]]
                    [foods.append(_z) for _z in value["vitamin"]]
                    [foods.append(_z) for _z in value["carbonWater"]]
                    [foods.append(_z) for _z in value["fat"]]
                    ary_can.append({"foods": foods, "name": key})
                _days.append({"cal_date": _i["cal_day"], "can": ary_can})
            res = FoodCatalogsRoute.foodCatalogsServiceImpl.updateCustDinner(
                custDinner=json.dumps(_days, ensure_ascii=False))
            if res["code"] == 200:
                return {'code': 200, 'data': res, 'message': ""}
            else:
                return {'code': res['code'], 'data': res, 'message': FoodCatalogsRoute.ERROR_CODE["100"]}

    @staticmethod
    @FoodcatAdm.get('/chooseOptData')
    def custom_choose_opt_data():
        _arry_opt = []
        load_data_flg = request.params.flg
        load_data_key = request.params.key
        if load_data_flg == "0":
            db_data_key = {"碳水化合": "carbonWater", "脂肪": "fat", "维生素": "vitamin", "蛋白质": "protein"}
            res = FoodCatalogsRoute.foodCatalogsServiceImpl.custom_choose_opt_data(flg=db_data_key[load_data_key],
                                                                                   key=None)
            if res["code"] == 200:
                _arry_db_data = res["data"]
                for idx in range(len(_arry_db_data)):
                    _arry_opt.append({
                        "label": _arry_db_data[idx]["key"],
                        "value": _arry_db_data[idx]["key"],
                        "key": idx
                    })
        elif load_data_flg == "1":
            res = FoodCatalogsRoute.foodCatalogsServiceImpl.custom_choose_opt_data(flg=None, key=load_data_key)
            if res["code"] == 200:
                _arry_db_data = res["data"]
                _split_db_data = [load_data for load_data in _arry_db_data if load_data["key"] == load_data_key]
                for idx in range(len(_split_db_data)):
                    _arry_opt.append({
                        "label": _split_db_data[idx]["name"],
                        "value": _split_db_data[idx]["name"],
                        "key": idx
                    })
        else:
            res = {"code": 200}
        return {'code': 200, 'data': _arry_opt, 'message': ""}
